//
//  Tool.swift
//  DKE-Album
//
//  Created by 杨东宝 on 2020/6/23.
//  Copyright © 2020 杨东宝. All rights reserved.
//

import UIKit
import AVFoundation

typealias Complate = ()->Void

class Tool: NSObject, AVAudioPlayerDelegate {
    var  audioPlayer:AVAudioPlayer?
     var complate:Complate?
    // 创建单例
    static let shared = Tool()
    // 设置初始化方法为私有，防止报错
    private override init() {
        
    }
    //MARK:- 读音
    func playAudioClick(urlString : String) {
        
        let url = URL(string: urlString)
        let configDefault = URLSessionConfiguration.default
        configDefault.timeoutIntervalForRequest = 15
        let session1 = URLSession(configuration: configDefault)
        let dataTask = session1.dataTask(with: url!, completionHandler: {(data,response,error)->Void in
            print(error ?? "")
            self.playsong(musicdata: data! as NSData)
        })
        dataTask.resume()
    }
    func playsong(musicdata:NSData){
        do{
            try! AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
            try! AVAudioSession.sharedInstance().setActive(true)
            audioPlayer = try AVAudioPlayer(data: musicdata as Data)
            audioPlayer?.prepareToPlay()
            audioPlayer?.play()
            audioPlayer?.delegate = self
        }catch {
            print(error)
        }
    }
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        DebugLog("播放完成");
        self.complate?();
        
    }
    ///label高度自适应
    /// - Parameters:
    ///   - text: 文字
    ///   - labelWidth: 最大宽度
    ///   - attributes: 字体，行距等
    /// - Returns: 高度
    func getAttributeStringWithString(_ string: String,labelWidth: CGFloat ,font:UIFont,lineSpace:CGFloat
    ) -> (NSMutableAttributedString,CGFloat){
        var attributedString = NSMutableAttributedString(string: string)
        let paragraphStye = NSMutableParagraphStyle()
        //调整行间距
        paragraphStye.lineSpacing = lineSpace
        paragraphStye.lineBreakMode = .byWordWrapping
        paragraphStye.alignment = .left;
        let rang = NSMakeRange(0, CFStringGetLength(string as CFString?))
        attributedString .addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStye, range: rang)
        attributedString .addAttribute(NSAttributedString.Key.font, value: font, range: rang)
        
        let size2 = CGSize(width: labelWidth, height: CGFloat(MAXFLOAT))//设置label的最大宽度
        let size:CGRect = attributedString.boundingRect(with: size2, options: [.usesLineFragmentOrigin,.usesFontLeading], context: nil)
        
        return (attributedString,ceil(size.size.height) + 1)
    }
}
extension String{
    
    /// 字符串的匹配范围 方法二(推荐)
    ///
    /// - Parameters:
    ///     - matchStr: 要匹配的字符串
    /// - Returns: 返回所有字符串范围
    func exMatchStrNSRange(matchStr: String) -> [NSRange] {
        var selfStr = self as NSString
        // var withStr = Array(count: (matchStr as NSString).length, repeatedValue: "X").joinWithSeparator("") //辅助字符串
        var withStr = Array(repeating: "X", count:(matchStr as NSString).length).joined(separator: "")
        
        if matchStr == withStr { withStr = withStr.lowercased()} //临时处理辅助字符串差错
        var allRange = [NSRange]()
        while selfStr.range(of: matchStr).location != NSNotFound {
            let range = selfStr.range(of: matchStr)
            allRange.append(NSRange(location: range.location,length: range.length))
            selfStr = selfStr.replacingCharacters(in: NSMakeRange(range.location, range.length), with: withStr) as NSString
        }
        return allRange
    }
}
